package com.heima.search.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author itlxc
 * @since 2024-07-28
 */
@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * 文章搜索功能
     * @param userSearchDto
     * @return
     * @throws IOException
     */
    @Override
    public ResponseResult search(UserSearchDto userSearchDto) throws IOException {
        // 1.参数校验
        if (ObjectUtil.isNull(userSearchDto) || StrUtil.isBlank(userSearchDto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        //异步调用 保存搜索记录
        if (ObjectUtil.isNotNull(user) && userSearchDto.getFromIndex() == 0) {
            apUserSearchService.insert(userSearchDto.getSearchWords(), user.getId());
        }
        // 2.创建request对象
        SearchRequest request = new SearchRequest("app_info_article");
        // 3.查询条件
        request.source().query(
                QueryBuilders.boolQuery()
                        .must(QueryBuilders.multiMatchQuery(userSearchDto.getSearchWords(), "title", "content"))
                        .filter(QueryBuilders.rangeQuery("publishTime").lt(userSearchDto.getMinBehotTime().getTime()))
        );
        // 4.分页条件
        request.source().from(0).size(userSearchDto.getPageSize());
        // 5.排序条件
        request.source().sort("publishTime", SortOrder.DESC);
        // 6.高亮条件
        request.source().highlighter(
                SearchSourceBuilder.highlight()
                        .field("title")
                        .preTags("<font style='color: red; font-size: inherit;'>")
                        .postTags("</font>")
        );
        // 7.发送请求
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        // 8.处理响应数据
        List<Map<String, Object>> result = handleResponse(response);
        return ResponseResult.okResult(result);
    }

    /**
     * 处理响应数据
     * @param response
     * @return
     */
    private List<Map<String, Object>> handleResponse(SearchResponse response) {
        SearchHit[] hits = response.getHits().getHits();
        List<Map<String, Object>> result = new ArrayList<>(hits.length);
        for (SearchHit hit : hits) {
            // 获取原始文档
            String source = hit.getSourceAsString();
            Map map = JSONUtil.toBean(source, Map.class);
            // 获取高亮字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (MapUtil.isNotEmpty(highlightFields)) {
                Text[] titles = highlightFields.get("title").getFragments();
                String title = StringUtils.join(titles);
                // 高亮标题
                map.put("h_title",title);
            } else {
                // 原始标题
                map.put("h_title",map.get("title"));
            }
            result.add(map);
        }
        return result;
    }
}
